package com.zjn.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DruidConfig {

    /*绑定yaml文件*/
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druidDataSource(){
        return new DruidDataSource();
    }

    /*后台监控功能实现*/
    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
        //后台需要有人登录：账号密码设置
        HashMap<String, String> initParameters = new HashMap<>();
        //登录的key是固定的，但value可以自定义
        initParameters.put("loginUserName","admin");
        initParameters.put("loginPassword","123456");
        /*访问权限设置：
            如果value为空：则代表任何人都可以访问
            如果value指定：则代表只有改用户可以访问
            禁止某个用户访问：initParameters.put("zjn","192.132.11.213");
         */
        initParameters.put("allow","");

        bean.setInitParameters(initParameters);//设置初始化参数
        return bean;
    }

    /*过滤器filter实现*/
    @Bean
    public FilterRegistrationBean webStartFilter(){
        FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<>();
        bean.setFilter(new WebStatFilter());
        //可以过滤的请求设置
        Map<String, String> initParameters = new HashMap<>();
        //这些文件不进行统计
        initParameters.put("exclusions","*.js,*.css,/druid/*,*.svg");
        bean.setInitParameters(initParameters);
        return bean;
    }

}
